package com.sinya.shoppingmall.utils;

import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.os.AsyncTask;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.ImageView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.sinya.shoppingmall.MyApplication;
import com.sinya.shoppingmall.bean.Constants;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

public class ImageLoaderUtils extends AsyncTask<String, Void, Bitmap> {

    ImageView imageview;
    private static HashMap<String, Bitmap> imageMaps = new HashMap<>();
    public static DisplayImageOptions options;
    public static ImageLoadingListener animateFirstListener = new MyImageLoaderListener();

    static {
        if (options == null) {
            initImageLoaderForHeader();
        }
    }

    public static void initImageLoaderForHeader() {
        // 使用DisplayImageOptions.Builder()创建DisplayImageOptions
        if (options == null) {
            options = new DisplayImageOptions.Builder()//
                    .bitmapConfig(Config.RGB_565)//
//                    .showStubImage(R.drawable.imgbg)// 设置图片下载期间显示的图片
//                    .showImageForEmptyUri(R.drawable.imgbg)// 设置图片Uri为空或是错误的时候显示的图片
//                    .showImageOnFail(R.drawable.imgbg)// 设置图片加载或解码过程中发生错误显示的图片
                    .cacheInMemory(true)// 设置下载的图片是否缓存在内存中
//                    .cacheOnDisk(true)// 设置下载的图片是否缓存在SD卡中
//                    .displayer(new RoundedBitmapDisplayer(360))  // 设置成圆角图片
                    .delayBeforeLoading(100)//
                    .build();// 创建配
        }
    }

    // [+] class

    static class MyImageLoaderListener extends SimpleImageLoadingListener {
        public final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>());

        @Override
        public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
            if (loadedImage != null) {
                ImageView imageView = (ImageView) view;
                // 是否第一次显示
                boolean firstDisplay = !displayedImages.contains(imageUri);
                if (firstDisplay) {
                    // 图片淡入效果
                    FadeInBitmapDisplayer.animate(imageView, 500);
                    displayedImages.add(imageUri);
                    int pos = imageUri.lastIndexOf('/');
                    //String pathfile = Company.getInstance().userFilePath + imageUri.substring(pos + 1);
                    String pathfile = FileHelper.getSDPath() + Constants.USER_PICTURE_NAME;
                    File myCaptureFile = new File(pathfile);
                    try {
                        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
                        loadedImage.compress(Bitmap.CompressFormat.JPEG, 80, bos);
                        bos.flush();
                        bos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    // [-] class


    public ImageLoaderUtils(ImageView view, String url) {
        LogUtils.I("Sinya", "SetImage: " + url);
        init(view);
        //TabBarActivity.mImageLoader.displayImage(url, view, options, animateFirstListener);
    }

    public ImageLoaderUtils(ImageView view, String uri, boolean isLocal) {
        if (uri == null) {
            return;
        }
        init(view);
        //TabBarActivity.mImageLoader.displayImage(uri, view, options, animateFirstListener);
    }

    public ImageLoaderUtils(ImageView view, String uri, ImageLoadingListener animate) {
        if (uri == null) {
            return;
        }
        init(view);
        //TabBarActivity.mImageLoader.displayImage(uri, view, options, animate);
    }

    public static void setImage(ImageView view, String uri, boolean isLocal) {
        new ImageLoaderUtils(view, uri, isLocal);
    }

    public void init(ImageView view) {
        /*if (TabBarActivity.mImageLoader == null) {
            TabBarActivity.initImageLoader(view.getContext());
        }*/
        if (options == null) {
            initImageLoaderForHeader();
        }
        if (animateFirstListener == null) {
            animateFirstListener = new MyImageLoaderListener();
        }
    }


    @Override
    protected Bitmap doInBackground(String... params) {
        String url = params[0];
        int pos = url.lastIndexOf('/');
        //String pathfile = Company.getInstance().userFilePath + url.substring(pos + 1);
        String pathfile = FileHelper.getSDPath() + Constants.USER_PICTURE_NAME;
        File file = new File(pathfile);
        if (!file.exists()) {
            //TODO 这里可以下载图片 并制定路径
            //HttpClient.download(pathfile, url);
            ImageLoaderUtils.transImage(pathfile, pathfile, 960, 70);
        }
        Bitmap bmp = decodeFile(pathfile);
        if (bmp == null) {
            //TODO 这里可以下载图片 并制定路径
            //HttpClient.download(pathfile, url);
            ImageLoaderUtils.transImage(pathfile, pathfile, 960, 70);
            bmp = decodeFile(pathfile);
        }

        if (bmp != null) {
            imageMaps.put(url, bmp);
        }
        return bmp;

//		HttpClient httpclient = HttpControl.getHttpClient();
//		HttpGet httpget = new HttpGet(params[0]);
//		Bitmap bmp = null;
//		try{
//			HttpResponse response = httpclient.execute(httpget);
//			HttpEntity entity = response.getEntity();
//			InputStream instream = entity.getContent();
//			bmp = BitmapFactory.decodeStream(instream);
//		}catch(Exception e){
//			Log.i("Sinya", e.toString());
//		}
//		return bmp;
    }

    @Override
    protected void onPostExecute(Bitmap result) {
        if (result != null) {
            imageview.setImageBitmap(result);
        }
        super.onPostExecute(result);
    }

    private static int mScrWidth = 0;
    private static int mScrHeight = 0;

    public static Bitmap decodeFile(String pathfile) {
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(pathfile, opts);

        if (mScrWidth == 0 || mScrHeight == 0) {
            DisplayMetrics dm = MyApplication.getContext().getResources().getDisplayMetrics();
            mScrWidth = dm.widthPixels;
            mScrHeight = dm.heightPixels;
        }

        int inSampleSize = calculateInSampleSize(opts, mScrWidth, mScrHeight);

        opts.inJustDecodeBounds = false;
        opts.inDither = true;
        opts.inPurgeable = true;
        opts.inTempStorage = new byte[12 * 1024];
        opts.inJustDecodeBounds = false;
        opts.inSampleSize = inSampleSize;
//        File file = new File(pathfile);
//        FileInputStream fs = null;
//        Bitmap bmp = null;
//        try {
//        	fs = new FileInputStream(file);
//        	bmp = BitmapFactory.decodeFileDescriptor(fs.getFD(), null, opts);
//        } catch (Exception e) {
//        	e.printStackTrace();
//        }finally{ 
//            if(fs!=null) {
//                try {
//                    fs.close();
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//        }	
//        return bmp;
        File file = new File(pathfile);
        Bitmap bmp = null;
        if (file.exists()) {
            bmp = BitmapFactory.decodeFile(pathfile, opts);
        }
        return bmp;
    }

    private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {

            final int halfHeight = height / 2;
            final int halfWidth = width / 2;

            while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth) {
                inSampleSize *= 2;
            }
        }
        return inSampleSize;
    }


    public static void transImage(String srcFile, String desFile, int maxSize, int quality) {
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(srcFile, opts);

        int inSampleSize = calculateInSampleSize(opts, maxSize, maxSize);

        opts.inJustDecodeBounds = false;
        opts.inDither = true;
        opts.inPurgeable = true;
        opts.inTempStorage = new byte[12 * 1024];
        opts.inJustDecodeBounds = false;
        opts.inSampleSize = inSampleSize;
        opts.inPreferredConfig = Config.RGB_565;

//        File file = new File(srcFile);
//        FileInputStream fs = null;
//        Bitmap bmp = null;
//        try {
//        	fs = new FileInputStream(file);
//        	bmp = BitmapFactory.decodeFileDescriptor(fs.getFD(), null, opts);
//        } catch (Exception e) {
//        	e.printStackTrace();
//        }finally{ 
//            if(fs!=null) {
//                try {
//                    fs.close();
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//        }

        Bitmap bmp = BitmapFactory.decodeFile(srcFile, opts);
        if (bmp == null) return;
        int w, h;
        int bw = bmp.getWidth();
        int bh = bmp.getHeight();
        if (bw >= bh) {
            w = maxSize;
            h = bh * w / bw;
        } else {
            h = maxSize;
            w = bw * h / bh;
        }
        Bitmap newbmp = Bitmap.createScaledBitmap(bmp, w, h, false);

        FileOutputStream fw;
        try {
            fw = new FileOutputStream(desFile);
            newbmp.compress(Bitmap.CompressFormat.JPEG, quality, fw);
            fw.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        newbmp.recycle();
        bmp.recycle();
        System.gc();
    }

    public static void transImage(Bitmap bmp, String desFile, int maxSize, int quality) {
        if (bmp == null) return;
        int w, h;
        int bw = bmp.getWidth();
        int bh = bmp.getHeight();
        if (bw >= bh) {
            w = maxSize;
            h = bh * w / bw;
        } else {
            h = maxSize;
            w = bw * h / bh;
        }
        Bitmap newbmp = Bitmap.createScaledBitmap(bmp, w, h, false);

        FileOutputStream fw;
        try {
            fw = new FileOutputStream(desFile);
            newbmp.compress(Bitmap.CompressFormat.JPEG, quality, fw);
            fw.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        newbmp.recycle();
        bmp.recycle();
        System.gc();
    }

    public static Bitmap getCirlceImage(Bitmap bmp) {
        int width = bmp.getWidth();
        int height = bmp.getHeight();

        int size = Math.min(width, height);
        Bitmap roundBitmap = Bitmap.createBitmap(size, size, Config.ARGB_8888);
        Canvas canvas = new Canvas(roundBitmap);
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
//		paint.setColor(0xffffffff);
        int s = size / 2;
        canvas.drawCircle(s, s, s, paint);
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
//	    canvas.drawBitmap(bmp, 0, 0, paint); //it will run faster if use this line code.
        int x = (width - size) / 2;
        int y = (height - size) / 2;
        Rect src = new Rect(x, y, x + size, y + size);
        Rect dst = new Rect(0, 0, size, size);
        canvas.drawBitmap(bmp, src, dst, paint);

        bmp.recycle();
        System.gc();
        return roundBitmap;
    }
}
